package com.smartsaas.ugclivii.loader;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smartsaas.ugclivii.ui.UiContext;
import lombok.AllArgsConstructor;
import nxopen.NXException;

import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.util.List;

@AllArgsConstructor
public class JsonLoader {
    public static <T> T loadJson(URI filePath,Class<T> clazz){
        File file = new File(filePath);
        String json = readJson(file);
        return JSONObject.parseObject(json ,clazz);
    }
    public static <T> T loadJson(String filePath,Class<T> clazz){
        File file = new File(filePath);
        String json = readJson(file);
        return JSONObject.parseObject(json ,clazz);
    }

    public static <T> List<T> loadJsonList(String filePath, Class<T> clazz){
        File file = new File(filePath);
        String json = readJson(file);
        return JSONObject.parseArray(json ,clazz);
    }

    private static String readJson(File file) {
        StringBuilder builder = new StringBuilder();
        if (file.exists()&&file.isFile()){
            try {
                FileInputStream fis = new FileInputStream(file);
                InputStreamReader ism = new InputStreamReader(fis, StandardCharsets.UTF_8);
                BufferedReader reader = new BufferedReader(ism);
                String line;
                while ((line = reader.readLine()) != null){
                    builder.append(line);
                }
            } catch (IOException e) {
            }
        }
        return builder.toString();
    }

    public static void save(File file, String json) throws IOException {
        if (!file.exists()){
            boolean newFile = file.createNewFile();
            if (newFile){
                FileOutputStream fos = new FileOutputStream(file);
                OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
                osw.write(json);
                osw.close();
            }
        }
    }
}
